<?php

namespace App\Imports;

use App\Models\Cashflow;
use App\Models\Category;
use App\Models\Member;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class CashflowImport implements ToCollection, WithHeadingRow, WithValidation
{
    private $user_id;
    public function __construct($user_id)
    {
        $this->user_id = $user_id;
    }


    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {
        DB::beginTransaction();
        try {
            $user = Member::query()->find($this->user_id);
            foreach ($rows as $row) {
                $type = $row['szlx'] == '收' ? Cashflow::TYPE_IN : Cashflow::TYPE_OUT;
                $date = Carbon::parse($row['rq']);
                $category =  Category::query()->firstOrCreate([
                    'user_id' => $user->id,
                    'name' => $row['fl'],
                    'type' => $type
                ], [
                    'icon' => 'red-packet'
                ]);
                $data = [
                    'type' => $type,
                    'cashbook_id' => $user->default_cashbook_id,
                    'category_id' => $category->id,
                    'amount' => $row['je'],
                    'date' => $date->toDateString(),
                    'remark' => $row['bz'] ?? null,
                    'year' => $date->year,
                    'month' => $date->month,
                    'day' => $date->day,
                    'user_id' => $user->id,
                ];
                Cashflow::query()->create($data);
            }
            DB::commit();
        } catch (\Throwable $th) {
            DB::rollBack();
            throw $th;
        }
    }

    public function headingRow(): int
    {
        return 2;
    }

    public function rules(): array
    {
        return [
            '*.fl' => 'required|string|max:4',
            '*.szlx' => ['required', Rule::in(['收', '支'])],
            '*.je' => 'required|numeric|min:0',
            '*.rq' => 'required|date',
            '*.bz' => 'nullable'
        ];
    }

    public function customValidationAttributes(): array
    {
        return [
            '*.fl' => '分类',
            '*.szlx' => '收支类型',
            '*.je' => '金额',
            '*.rq' => '日期',
            '*.bz' => '备注'
        ];
    }
}
